﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Threading;

namespace EmProductCenter.ePweb
{
    /// <summary>
    /// DataInfo 的摘要说明
    /// </summary>
    public class DataInfo : IHttpHandler
    {
        Common.CommonClass common = new Common.CommonClass();
        LYM.CommonWeb.SocketClient client = new LYM.CommonWeb.SocketClient();

        public void ProcessRequest(HttpContext context)
        {
            string strAction = context.Request["action"].ToString();
            StringBuilder strReturn = new StringBuilder();
            switch (strAction)
            {
                //生成日历
                case "GetThisMonthHtml":
                    strReturn = GetThisMonthHtml(context);
                    break;
                //生成当前天的数据
                case "GetThisDayInfo":
                    strReturn = GetThisDayInfo(context);
                    break;
                //获取解冻数据
                case "GetNewDateModel":
                    strReturn = GetNewDateModel(context);
                    break;
                case "GetWeatherData":
                    strReturn.Append(GetWeatherData());
                    break;
                case "GetStockNews":
                    strReturn.Append(GetStockNews(context));
                    break;
            }
            context.Response.Write(strReturn);
        }

        /// <summary>
        /// 天气预报数据
        /// </summary>
        /// <returns></returns>
        private string GetWeatherData()
        {
            string url = "http://cmsservice.emoney.cn/comm/weather.ashx";
            string resultStr = client.GetClientBySocket(url);
            object o = common.JsonToObj(resultStr, new WeatherData().GetType(), Encoding.UTF8);
            WeatherData wd = o as WeatherData;
            url = "http://cmsservice.emoney.cn/hangqing/bkqr.ashx";
            resultStr = client.GetClientBySocket(url);
            o = common.JsonToObj(resultStr, new BanKuaiQiangRuo().GetType(), Encoding.UTF8);
            BanKuaiQiangRuo bkqr = o as BanKuaiQiangRuo;
            if (bkqr != null)
            {
                foreach (BanKuai bk in bkqr.qsbk)
                {
                    wd.bkqr = bk.name + "|" + wd.bkqr;
                }
            }
            wd.long_strategy = wd.bkqr;
            return common.ObjToJson<WeatherData>(wd);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetStockNews(HttpContext context)
        {
            string resultStr = "";
            if (context.Request["url"] != null)
            {
                string url = context.Request["url"];
                url = context.Server.UrlDecode(url);
                resultStr = client.GetClientBySocket(url, Encoding.UTF8);
                object o = common.JsonToObj(resultStr, new StockNewsRoot().GetType(), Encoding.UTF8);
                StockNewsRoot wd = o as StockNewsRoot;
                if (wd != null && wd.root != null && wd.root[0].data.Count > 0)
                    resultStr = common.ObjToJson(wd.root[0].data[0]);
                else
                    resultStr = "";
            }
            return resultStr;
        }

        /// <summary>
        /// 获取解冻数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StringBuilder GetNewDateModel(HttpContext context)
        {
            StringBuilder strReturn = new StringBuilder();

            DateTime thisday = DateTime.Now.Date;
            if (context.Request["thisday"] != null && context.Request["thisday"] != "")
            {
                try
                {
                    thisday = Convert.ToDateTime(context.Request["thisday"]).Date;
                }
                catch
                {
                    thisday = DateTime.Now.Date;
                }
            }

            string jiedong = "";
            string jiedongmore = "";
            try
            {
                NewDateService.EPioneerData service = new NewDateService.EPioneerData();
                NewDateService.NewDateModel[] list = service.GetNewDateModel(thisday);
                for (int i = 0; i < list.Length; i++)
                {
                    if (i < 3)
                    {
                        jiedong += "<span class='pointunderline' onclick=\"GoToDetail('" + list[i].Code + "');\">" + list[i].Name + "</span>";
                    }
                    else
                    {
                        jiedongmore += "<span style='cursor:pointer;' onclick=\"GoToDetail('" + list[i].Code + "');\">" + list[i].Name + "</span>";
                    }
                }
            }
            catch
            {
                jiedong = "";
                jiedongmore = "";
            }
            if (jiedongmore != "")
            {
                jiedong = "<div class=\"more\" onclick=\"More(4);\"></div>" + jiedong;
            }
            if (jiedong.Length == 0)
            {
                jiedong = "无";
            }
            string[] ss = new string[] { jiedong, jiedongmore };
            strReturn.AppendLine(common.ObjToJson(ss, Encoding.UTF8));
            return strReturn;
        }

        /// <summary>
        /// 生成当前天的数据
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StringBuilder GetThisDayInfo(HttpContext context)
        {
            StringBuilder strReturn = new StringBuilder();

            DateTime thisday = DateTime.Now.Date;
            if (context.Request["thisday"] != null && context.Request["thisday"] != "")
            {
                try
                {
                    thisday = Convert.ToDateTime(context.Request["thisday"]).Date;
                }
                catch
                {
                    thisday = DateTime.Now.Date;
                }
            }
            string shengou = "";
            string shangshi = "";
            string zhongquanhao = "";
            string zhongquanli = "";
            string jiedong = "";
            string shengoumore = "";
            string shangshimore = "";
            string zhongquanhaomore = "";
            string zhongquanlimore = "";
            string jiedongmore = "";
            var listResult = LYM.CommonWeb.DataCache.GetCache("listResult");
            if (listResult == null || listResult.ToString() == "")
            {
                string url = "http://cmsservice.emoney.cn/stock/newstocklist.ashx";
                string resultStr = client.GetClientBySocket(url);
                listResult = common.JsonToObj(resultStr, new List<News>().GetType(), Encoding.UTF8);
                if (listResult != null)
                    LYM.CommonWeb.DataCache.SetCache("listResult", listResult);
            }
            var listNews = listResult as List<News>;
            int iSS = 0;
            int iSG = 0;
            int iZQH = 0;
            int iZQL = 0;
            if (listNews != null)
            {
                foreach (News news in listNews)
                {
                    if (news.ssrq.Date == thisday)
                    {
                        if (iSS < 3)
                        {
                            iSS++;
                            shangshi += "<span class='pointunderline' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                        }
                        else
                        {
                            shangshimore += "<span style='cursor:pointer;' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                        }
                    }

                    if (news.fxrq.Date == thisday)
                    {
                        if (iSG < 3)
                        {
                            iSG++;
                            shengou += "<span class='pointunderline' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                        }
                        else
                        {
                            shengoumore += "<span style='cursor:pointer;' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                        }
                    }


                    if (news.zqhggr.Date == thisday)
                    {
                        if (iZQH < 3)
                        {
                            iZQH++;
                            zhongquanhao += "<span class='pointunderline' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                        }
                        else
                        {
                            zhongquanhaomore += "<span style='cursor:pointer;' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                        }

                        if (!float.Equals(0, news.fxzql))
                        {
                            if (iZQL < 3)
                            {
                                iZQL++;
                                zhongquanli += "<span class='pointunderline' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                            }
                            else
                            {
                                zhongquanlimore += "<span style='cursor:pointer;' onclick=\"GoToDetail('" + news.gpdm + "');\">" + news.gpjc + "</span>";
                            }
                        }

                    }
                }
            }

            if (shangshimore != "")
            {
                shangshi = "<div class=\"more\" onclick=\"More(1);\"></div>" + shangshi;
            }
            if (shengoumore != "")
            {
                shengou = "<div class=\"more\" onclick=\"More(0);\"></div>" + shengou;
            }
            if (zhongquanhaomore != "")
            {
                zhongquanhao = "<div class=\"more\" onclick=\"More(2);\"></div>" + zhongquanhao;
            }
            if (zhongquanlimore != "")
            {
                zhongquanli = "<div class=\"more\" onclick=\"More(3);\"></div>" + zhongquanli;
            }


            if (shangshi.Length == 0)
            {
                shangshi = "无";
            }
            if (shengou.Length == 0)
            {
                shengou = "无";
            }
            if (zhongquanhao.Length == 0)
            {
                zhongquanhao = "无";
            }
            if (zhongquanli.Length == 0)
            {
                zhongquanli = "无";
            }
            if (jiedong.Length == 0)
            {
                jiedong = "无";
            }
            string[] ss = new string[] { shengou, shangshi, zhongquanhao, zhongquanli, jiedong, shengoumore, shangshimore, zhongquanhaomore, zhongquanlimore, jiedongmore };
            strReturn.AppendLine(common.ObjToJson(ss, Encoding.UTF8));

            return strReturn;
        }

        /// <summary>
        /// 生成日历
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StringBuilder GetThisMonthHtml(HttpContext context)
        {
            StringBuilder strReturn = new StringBuilder();
            DateTime startDate = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-1");
            if (context.Request["startDate"] != null && context.Request["startDate"] != "")
            {
                DateTime sDate = Convert.ToDateTime(context.Request["startDate"]);
                startDate = Convert.ToDateTime(sDate.Year + "-" + sDate.Month + "-1");
            }
            if (context.Request["preOrnext"] != null && context.Request["preOrnext"] != "")
            {
                string preOrnext = context.Request["preOrnext"];
                if (preOrnext == "1")
                    startDate = startDate.AddMonths(-1);
                else if (preOrnext == "2")
                    startDate = startDate.AddMonths(1);
                else if (preOrnext == "0")
                    startDate = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-1");
            }

            var listResult = LYM.CommonWeb.DataCache.GetCache("listResult");
            if (listResult == null || listResult.ToString() == "")
            {
                string url = "http://cmsservice.emoney.cn/stock/newstocklist.ashx";
                string resultStr = client.GetClientBySocket(url);
                listResult = common.JsonToObj(resultStr, new List<News>().GetType(), Encoding.UTF8);
                if (listResult != null)
                    LYM.CommonWeb.DataCache.SetCache("listResult", listResult);
            }

            DateTime endDate = startDate.AddMonths(1);
            StringBuilder strTr = new StringBuilder();
            int days = endDate.AddDays(-1).Day;
            int i = 1;
            int j = GetThisDay(startDate.DayOfWeek);
            int taday = DateTime.Now.Day;
            strTr.Append("<tr><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\">日</td><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\"> 一</td><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\">二</td><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\">三</td><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\">四</td><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\">五</td><td width=\"24\" height=\"18\" align=\"center\" valign=\"middle\" style=\"font-size: 12px;\">六</td></tr>");
            //控制日期
            while (i <= days)
            {
                strTr.Append("<tr>");
                //控制星期
                for (int k = 0; k < j; k++)
                {
                    strTr.Append("<td width=\"24\" height=\"14\" align=\"center\" valign=\"middle\">&nbsp;</td>");
                }
                for (; j < 7; j++)
                {
                    if (i <= days)
                    {
                        string thisday = startDate.ToString("yyyy年MM月") + i + "日";
                        var listNews = listResult as List<News>;
                        DateTime thatDay = Convert.ToDateTime(thisday).Date;
                        if (listNews != null && listNews.Where(p => p.ssrq.Date == thatDay || p.fxrq.Date == thatDay || (p.zqhggr.Date == thatDay && !float.Equals(0, p.fxzql))).Count() != 0)
                        {
                            strTr.Append("<td width=\"24\" height=\"14\" align=\"center\" valign=\"middle\" bgcolor=\"#FFCC33\" style=\"cursor:pointer;\" onclick=\"GetThisDayInfo('" + thisday + "');\">" + i + "</td>");
                        }
                        else
                        {
                            strTr.Append("<td width=\"24\" height=\"14\" align=\"center\" valign=\"middle\" style=\"cursor:pointer;\" onclick=\"GetThisDayInfo('" + thisday + "');\">" + i + "</td>");
                        }
                    }
                    else
                    {
                        strTr.Append("<td width=\"24\" height=\"14\" align=\"center\" valign=\"middle\">&nbsp;</td>");
                    }
                    i++;
                }
                j = 0;
                strTr.Append("</tr>");
            }

            string[] ss = new string[] { strTr.ToString(), startDate.ToString("yyyy年MM月") };
            strReturn.AppendLine(common.ObjToJson(ss, Encoding.UTF8));
            return strReturn;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private int GetThisDay(DayOfWeek week)
        {
            int result = 0;
            switch (week)
            {
                case DayOfWeek.Tuesday:
                    result = 2;
                    break;
                case DayOfWeek.Wednesday:
                    result = 3;
                    break;
                case DayOfWeek.Thursday:
                    result = 4;
                    break;
                case DayOfWeek.Friday:
                    result = 5;
                    break;
                case DayOfWeek.Saturday:
                    result = 6;
                    break;
                case DayOfWeek.Monday:
                    result = 1;
                    break;
                default:
                    break;
            }
            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    #region sastocknews
    public class StockNewsRoot
    {
        List<StockNewsData> _root;

        public List<StockNewsData> root
        {
            get { return _root; }
            set { _root = value; }
        }
    }
    public class StockNewsData
    {
        List<StockNews> _data;

        public List<StockNews> data
        {
            get { return _data; }
            set { _data = value; }
        }
    }
    public class StockNews
    {
        string content;

        public string Content
        {
            get { return content; }
            set { content = value; }
        }
        string title;

        public string Title
        {
            get { return title; }
            set { title = value; }
        }
        string date;

        public string Date
        {
            get
            {
                if (!string.IsNullOrEmpty(date) && date.Length == 8)
                {
                    return date.Substring(0, 4) + "-" + date.Substring(4, 2) + "-" + date.Substring(6, 2);
                }
                else
                    return "";
            }
            set { date = value; }
        }
        string newsID;

        public string NewsID
        {
            get { return newsID; }
            set { newsID = value; }
        }
        string secuCode;

        public string SecuCode
        {
            get { return secuCode; }
            set { secuCode = value; }
        }
        string secuName;

        public string SecuName
        {
            get { return secuName; }
            set { secuName = value; }
        }
    }
    #endregion

    public class News
    {
        /// <summary>
        /// 股票代码
        /// </summary>
        public string gpdm
        {
            get;
            set;
        }

        /// <summary>
        /// 股票简称
        /// </summary>
        public string gpjc
        {
            get;
            set;
        }

        /// <summary>
        /// 中签率
        /// </summary>
        public float fxzql
        {
            get;
            set;
        }

        /// <summary>
        /// 中签号公布日
        /// </summary>
        public DateTime zqhggr
        {
            get;
            set;
        }

        /// <summary>
        /// 上市日期
        /// </summary>
        public DateTime ssrq
        {
            get;
            set;
        }

        /// <summary>
        /// 申购日期
        /// </summary>
        public DateTime fxrq
        {
            get;
            set;
        }

    }

    public class BanKuaiQiangRuo
    {
        List<BanKuai> _qsbk;

        public List<BanKuai> qsbk
        {
            get { return _qsbk; }
            set { _qsbk = value; }
        }

        List<BanKuai> _rsbk;

        public List<BanKuai> rsbk
        {
            get { return _rsbk; }
            set { _rsbk = value; }
        }
    }

    public class BanKuai
    {
        string _stockid;

        public string stockid
        {
            get { return _stockid; }
            set { _stockid = value; }
        }
        string _name;

        public string name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class WeatherData
    {
        public DateTime date
        {
            get;
            set;
        }
        public string sdate
        {
            set
            {
                date = date;
            }
            get { return date.ToString("yyyyMMdd"); }
        }

        public string time
        {
            set
            {
                date = date;
            }
            get { return date.ToString("HHmm"); }
        }
        string _weather;
        public string weather
        {
            get { return _weather; }
            set { _weather = value; }
        }
        string _content;

        public string content
        {
            get { return _content; }
            set { _content = value; }
        }
        string _posi;

        public string posi
        {
            get { return _posi; }
            set { _posi = value; }
        }
        string _short_strategy;

        public string short_strategy
        {
            get { return _short_strategy; }
            set { _short_strategy = value; }
        }
        string _long_strategy;

        public string long_strategy
        {
            get { return _long_strategy; }
            set { _long_strategy = value; }
        }

        string _bkqr;

        public string bkqr
        {
            get { return _bkqr; }
            set { _bkqr = value; }
        }
    }
}